/**
 * 拷贝对象
 * @param params 需要拷贝的对象
 * @returns any
 */
export const cp = (params: object) => {
  try {
    const s = JSON.stringify(params)
    return JSON.parse(s)
  } catch (e) {
    throw new Error(e?.toString())
  }
}

export const objToEmpty = (obj: objType ) => {
  Object.keys(obj).forEach((key) => {
    const s: string = Object.prototype.toString.call(obj[key]).slice(8, -1)
    switch (s) {
      case "Number":
        obj[key] = 0;
        break;
      case "Boolean":
        obj[key] = false;
        break;
      case "String":
        obj[key] = '';
        break;
      case "Date":
        obj[key] = new Date();
        break;
      case "Object":
        obj[key] = {};
        break;
      case "Array":
        obj[key] = [];
        break;
      default:
        obj[key] = '';
    }
  })
}

export const copyClipboard = (text: string) => {
  const input = document.createElement('input');
  input.setAttribute('readonly', 'readonly');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.setSelectionRange(0, 9999);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
}

export const passwordCheck = (password: string) => {
  const pwdRegex = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]){8,30}');
  return pwdRegex.test(password);
}

/**
 * 将数据转换为树形结构
 * @param data 原始数据
 * @param primaryKey 当前数据数据判断的字段
 * @param parentKey 父级数据判断的字段
 * @param parentId 父级数据判断的值
 */
export const dataToTree = (data: any[], primaryKey: string, parentKey: string ,parentId: number|string ) => {
  const tree: any[] = [];
  data.forEach((item: any) => {
    if (item[parentKey] === parentId) {
      const children = dataToTree(data, primaryKey, parentKey, item[primaryKey]);
      if (children.length > 0) {
        item.children = children;
      }
      tree.push(item);
    }
  });
  return tree;
}

export const dataToTreeArray = (data: any[], parentKey: string, childKey: string) => {
  const map: any = {};
  data.forEach((item: any) => {
    const key = item[parentKey];
    item['label'] = item[childKey];
    item['key'] = item[childKey];
    if (!map[key]) {
      map[key] = {
        label: key,
        key: key,
        children: [item],
      };
    }else {
      map[key]['children'].push(item);
    }
  });
  return Object.values(map);
}

/**
 * 将数据转换为枚举映射表
 * @param data 原始数据
 * @param type 值的类型 'string'|'number'
 * @param fieldKey 转变到的字段
 * @param valueKey 值的字段
 * @param pcode 处理判断父级的字段
 */
export const dataToEnumMap = (data: any[], type: 'string'|'number', fieldKey: string, valueKey: string, pcode: string) : EnumMap[] => {
  const map: EnumMap[] = [];
  data.forEach((item: any) => {
    const mapItem: EnumMap = {
      label: item[fieldKey],
      pCode: item[pcode],
    }
    if (type === 'number') {
      mapItem['key'] = item[valueKey];
    } else {
      mapItem['value'] = item[valueKey];
    }
    map.push(mapItem);
  })
  return map;
}
